package com.neu.fenli2023623.security;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neu.fenli2023623.util.JwtUtils;
import com.neu.fenli2023623.util.RedisCache;
import com.neu.fenli2023623.util.ResultVo;
import com.neu.fenli2023623.util.ServerCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        if (StrUtil.isEmptyOrUndefined(token)) {//用户登录时还没有token信息，直接放行，请求LoginFilter
            filterChain.doFilter(request,response);
            return;
        }

        Claims claims = jwtUtils.getClaimsByToken(token);
        if (claims == null) {//token不为空，但是不能当前系统发出的
            String s = new ObjectMapper().writeValueAsString(ResultVo.error(ServerCode.ERR_JWT_PARSE.getMessage()));
            response.getWriter().println(s);
            return;
        }
        boolean tokenExpired = jwtUtils.isTokenExpired(claims);
        if (tokenExpired) {//如果过期，则重新登录
            String s = new ObjectMapper().writeValueAsString(ResultVo.error("登录失效了，请重新登录"));
            response.getWriter().println(s);
            return;
        }
        //如果能走到这里，说明token有效
        String userName = claims.getSubject();//取得用户名信息
        //UserDetails userDetails = userDetailsService.loadUserByUsername(userName);//调用后台接口，得到用户信息及权限等
        //直接从缓存中抓取数据，不再走物理数据库，提交效率
        LoginUser userDetails = (LoginUser) redisCache.getCacheObject("neu:" + userName);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        //把认证信息放到SecurityContext中，将来做鉴权时使用
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}